<?php
/**
 * Model Table Mapping Update Script
 * Update all Model files to use correct gf_ prefixed table names
 * 
 * Usage: php update_model_mappings.php
 */

echo "🔧 Updating Model table mappings to use gf_ prefixed names...\n\n";

// Define table mapping updates based on our database analysis
$modelUpdates = [
    // File path => [old_table_name => new_table_name]
    '/webman/app/common/model/apps/AppsModel.php' => ['apps' => 'gf_apps'],
    '/webman/app/common/model/apps/AppsAppsModel.php' => ['apps_apps' => 'gf_et_apps_apps'],
    '/webman/app/common/model/apps/AppsEventModel.php' => ['apps_event' => 'gf_et_apps_event'],
    '/webman/app/common/model/apps/AppsWebModel.php' => ['apps_web' => 'gf_et_apps_web'],
    '/webman/app/common/model/merchant/MerchantModel.php' => ['merchants' => 'gf_merchants'],
    '/webman/app/common/model/merchant/MerchantApiKeyModel.php' => ['merchant_api_keys' => 'gf_api_keys'],
    '/webman/app/common/model/merchant/MerchantStatsModel.php' => ['merchant_stats' => 'gf_stats_daily'],
    '/webman/app/common/model/users/UsersModel.php' => ['users' => 'gf_et_users'],
];

$baseDir = __DIR__ . '/../../..';
$updatedModels = [];
$errors = [];

foreach ($modelUpdates as $relativePath => $tableMappings) {
    $fullPath = $baseDir . $relativePath;
    
    if (!file_exists($fullPath)) {
        echo "⚠️  File not found: $relativePath\n";
        continue;
    }
    
    echo "Processing: $relativePath\n";
    
    $content = file_get_contents($fullPath);
    $originalContent = $content;
    $fileUpdated = false;
    
    foreach ($tableMappings as $oldTable => $newTable) {
        // Update tableName() method
        $pattern = "/public\s+static\s+function\s+tableName\(\)\s*:\s*string\s*{\s*return\s+['\"]" . preg_quote($oldTable, '/') . "['\"];\s*}/";
        $replacement = "public static function tableName(): string { return '$newTable'; }";
        
        $newContent = preg_replace($pattern, $replacement, $content);
        if ($newContent !== $content) {
            echo "  ✅ Updated tableName(): $oldTable → $newTable\n";
            $content = $newContent;
            $fileUpdated = true;
        } else {
            // Try alternative pattern matching
            $pattern2 = "/return\s+['\"]" . preg_quote($oldTable, '/') . "['\"];/";
            if (preg_match($pattern2, $content)) {
                $content = preg_replace($pattern2, "return '$newTable';", $content);
                echo "  ✅ Updated return statement: $oldTable → $newTable\n";
                $fileUpdated = true;
            }
        }
    }
    
    if ($fileUpdated) {
        // Backup original file
        $backupPath = $fullPath . '.backup.' . date('YmdHis');
        file_put_contents($backupPath, $originalContent);
        
        // Update the file
        file_put_contents($fullPath, $content);
        
        $updatedModels[] = $relativePath;
        echo "  💾 Updated and backup created\n";
    } else {
        echo "  ℹ️  No changes needed\n";
    }
    
    echo "\n";
}

echo "📊 SUMMARY:\n";
echo "==================================================\n";
echo "Models updated: " . count($updatedModels) . "\n";
echo "Errors: " . count($errors) . "\n";

if (count($updatedModels) > 0) {
    echo "\nUpdated models:\n";
    foreach ($updatedModels as $model) {
        echo "  ✅ $model\n";
    }
}

if (count($errors) > 0) {
    echo "\nErrors encountered:\n";
    foreach ($errors as $error) {
        echo "  ❌ $error\n";
    }
}

echo "\n🔍 Verification:\n";
echo "==================================================\n";

// Verify the updates by checking a few files
foreach ($updatedModels as $modelPath) {
    $fullPath = $baseDir . $modelPath;
    if (file_exists($fullPath)) {
        $content = file_get_contents($fullPath);
        if (preg_match("/tableName\(\).*return\s+['\"](gf_[a-zA-Z0-9_]+)['\"]/", $content, $matches)) {
            echo "✅ $modelPath now uses table: " . $matches[1] . "\n";
        } else {
            echo "⚠️  Could not verify table name for: $modelPath\n";
        }
    }
}

echo "\n🎉 Model table mapping update completed!\n";
echo "\n💡 Next steps:\n";
echo "1. Test your application to ensure models work correctly\n";
echo "2. Check for any other hardcoded table references in controllers\n";
echo "3. Run database queries to verify table access\n";
echo "4. Backup files are saved with .backup. timestamp extension\n";

?>